import { getToken, setToken } from '@/utils/auth'
import { syslogin, sysprofile, sysUser } from '@/api/user'
import { Message } from 'element-ui'
import Router from '@/router'
import arrRoutes from '@/router/modules/index'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: ''
}
const mutations = {
  setTokens(state, val) {
    state.token = val
    setToken(val)
  },
  setUserInfo(state, val) {
    state.userInfo = val
  },
  loginOut() {
    // mutations 调用 mutations 方法 this 相当于 组件中this.$store
    this.commit('user/setTokens', '')
    this.commit('user/setUserInfo', '')
    // 退出登录的时候都会调用这个方法,退出时要重置路由
    resetRouter()
  }
}
const actions = {
  async toLogin(store, val) {
    const res = await syslogin(val)
    store.commit('setTokens', res.data)
    Message.success(res.message)
  },
  async getUserInfo({ commit }) {
    const res = await sysprofile()
    const res2 = await sysUser(res.data.userId)
    /*
    合并对象的方法
    1. 展开运算符 --- {...res, ...res2}
    2. Object.assign(指定对象, 其他对象) 将其他对象的可枚举属性复制到指定对象上,一层数据结构算深拷贝,多层数据结构算浅拷贝
    */
    commit('setUserInfo', Object.assign(res.data, res2.data))
    // 获取到用户信息后,为角色分配权限 匹配用户路由权限信息,使用addRoutes方法动态添加路由
    // 调用routes模块中的方法存储路由配置信息,实现菜单响应式更新
    // console.log(res.data)
    const newArr = arrRoutes.filter((item) => {
      return res.data.roles.menus.includes(item.meta.name)
    })
    Router.addRoutes([...newArr, { path: '*', redirect: '/404', hidden: true }])
    commit(
      'routes/setRoutesList',
      [...newArr, { path: '*', redirect: '/404', hidden: true }],
      { root: true }
    )
    // console.log(newArr, '111')
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
